package com.jcl.cloud.services.login.factory;

import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.openqa.selenium.WebDriver;

public class WebDriverPool {

    private static GenericKeyedObjectPool<String, WebDriver> pool;
    private static WebDriverFactory webDriverFactory;
    private static GenericKeyedObjectPoolConfig genericKeyedObjectPoolConfig;


    static {

        webDriverFactory = new WebDriverFactory();
        genericKeyedObjectPoolConfig = new GenericKeyedObjectPoolConfig();
        genericKeyedObjectPoolConfig.setMaxTotalPerKey(5);
        genericKeyedObjectPoolConfig.setMinIdlePerKey(2);
        genericKeyedObjectPoolConfig.setMaxTotal(10);

        genericKeyedObjectPoolConfig.setBlockWhenExhausted(true);
        genericKeyedObjectPoolConfig.setMaxWaitMillis(10 * 1000);
        genericKeyedObjectPoolConfig.setFairness(true);
        genericKeyedObjectPoolConfig.setTestOnBorrow(true);
        genericKeyedObjectPoolConfig.setTestOnReturn(true);
        genericKeyedObjectPoolConfig.setTestOnCreate(true);
        genericKeyedObjectPoolConfig.setTestWhileIdle(true);
        genericKeyedObjectPoolConfig.setTimeBetweenEvictionRunsMillis(20 * 1000);
        genericKeyedObjectPoolConfig.setNumTestsPerEvictionRun(1);
        genericKeyedObjectPoolConfig.setMinEvictableIdleTimeMillis(10 * 1000);
        //genericKeyedObjectPoolConfig.setSoftMinEvictableIdleTimeMillis(3*1000);
    }


    public static void init() {
        pool = new GenericKeyedObjectPool<String, WebDriver>(webDriverFactory, genericKeyedObjectPoolConfig);
    }


    public static GenericKeyedObjectPool<String, WebDriver> getInstance() {
        if (pool == null) {
            synchronized (GenericKeyedObjectPool.class) {
                if (pool == null) {
                    init();
                    return pool;
                }
            }
        }
        return pool;
    }

    public static void close() {
        if (pool != null) {
            pool.close();
        }
    }


}
